package mqtt

import (
	mqtt "github.com/alibabacloud-go/onsmqtt-20200420/client"
	"testkjcld.bhecard.com/gitlab/kit/esim/config"
	"testkjcld.bhecard.com/gitlab/kit/esim/log"
)

type Publisher struct {
	client *MQTTClient

	logger log.Logger

	conf config.Config
}

type PublisherOption func(*Publisher)

/*发送消息方法集*/
func NewPublisher(options ...PublisherOption) *Publisher {
	p := &Publisher{}

	for _, option := range options {
		option(p)
	}

	if p.conf == nil {
		p.conf = config.NewNullConfig()
	}

	if p.logger == nil {
		p.logger = log.NewLogger()
	}

	/*初始化客户端*/
	var cliOpt MQTTClientOptions
	p.client = newMQTTClient(
		cliOpt.WithLogger(p.logger),
		cliOpt.WithConf(p.conf))
	return p
}

type PublisherOptions struct{}

func (p *PublisherOptions) WithPublisherConf(conf config.Config) PublisherOption {
	return func(p *Publisher) {
		p.conf = conf
	}
}

func (p *PublisherOptions) WithPublisherLogger(logger log.Logger) PublisherOption {
	return func(p *Publisher) {
		p.logger = logger
	}
}

/*从服务端应用向微消息队列MQTT版发送单条消息*/
func (p *Publisher) SendMessage(topic, body string) (*mqtt.SendMessageResponse, error) {
	request := &mqtt.SendMessageRequest{}
	request.MqttTopic = &topic
	request.InstanceId = &p.client.instanceId
	request.Payload = &body
	return p.client.mqttClient.SendMessage(request)
}
